package com.probox.common.entity.service.job;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.RechargeInfo;
import com.probox.common.entity.domain.order.OrderRecharge;
import com.probox.common.entity.domain.platfom.PlatformStore;
import com.probox.common.entity.mapper.order.OrderRechargeMapper;
import com.probox.common.entity.service.order.IOrderInfoShareService;
import com.probox.common.entity.service.platfom.IPlatformCmsService;
import com.probox.common.entity.service.platfom.IPlatformStoreService;
import com.probox.customer.api.domain.CustomerFundDetailVo;
import com.probox.common.entity.domain.job.OrderInfo;
import com.probox.common.entity.domain.job.OrderPayInfo;
import com.probox.common.entity.mapper.job.JobOrderInfoMapper;
import com.probox.common.entity.service.customer.ICustomerFundDetailService;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import com.probox.order.api.domain.ProfitShareReceiver;
import com.probox.order.api.domain.ProfitShareVo;
import com.probox.order.api.utils.WechatV3Payment;
import com.probox.platform.api.domain.PlatformGeneralsettingsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
@Transactional
public class JobOrderInfoServiceImpl extends ServiceImpl<JobOrderInfoMapper, OrderInfo> implements IOrderInfoService {

    private static final Logger log = LoggerFactory.getLogger(JobOrderInfoServiceImpl.class);

    @Autowired
    private JobOrderInfoMapper jobOrderInfoMapper;

    @Autowired
    private OrderRechargeMapper orderRechargeMapper;



    @Autowired
    private IOrderInfoParentService parentService;

    @Autowired
    private IOrderPayInfoService payInfoService;


    @Autowired
    private IPlatformGeneralsettingsService platformGeneralsettingsService;

    @Autowired
    private ICustomerFundDetailService iCustomerFundDetailService;

    @Autowired
    private IOrderPayInfoService orderPayInfoService;

    @Autowired
    private IOrderInfoShareService orderInfoShareService;

    @Autowired
    private IPlatformStoreService platformStoreService;

    @Override
    public List<OrderInfo> selectShipOrder() {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("send_status", SendStatusEnum.ship.getKey());
        queryWrapper.le("auto_receive_time", new Date());

        return jobOrderInfoMapper.selectList(queryWrapper);
    }

    @Override
    public void autoShip(List<OrderInfo> list) {
        if (ObjectUtil.isNotEmpty(list)) {
            Date now = new Date();

//            MessageEntity entity = null;
            for (OrderInfo order : list) {
                order.setSendTime(now);
                order.setSendStatus(SendStatusEnum.receive.getKey());


            }
            this.updateBatchById(list);
        }

    }

    /**
     * 查询可分账的订单
     *
     * @return
     */
    @Override
    public void selectProfit() {
        List<OrderInfo> list = null;

        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", IsSharedEnum.unShared.getKey());
        list = jobOrderInfoMapper.selectList(queryWrapper);
        log.info("\n=======待分账的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Date now = new Date();
            PlatformGeneralsettingsVo pgVo = null;

            Iterator<OrderInfo> iterator = list.iterator();
            while (iterator.hasNext()) {
                OrderInfo info = iterator.next();
                pgVo = platformGeneralsettingsService.get(info.getPlatformUid());
                log.info("\n==========获取平台配置parameter:{}==========\n===========result:{}===========\n",
                        info.getPlatformUid(), JSONObject.toJSONString(pgVo));
                if (ObjectUtil.isEmpty(pgVo)) {
                    iterator.remove();
                } else {
                    int thaw = 7;
                    if (ObjectUtil.isNotEmpty(pgVo.getOrderMoney())) {
                        thaw = Convert.toInt(pgVo.getOrderMoney(), 7);
                    }
                    log.info("\n=========收货后：{}天解冻分润=========\n", thaw);
                    DateTime time = DateUtil.offsetDay(info.getReceiveTime(), thaw);
                    if (time.after(now)) iterator.remove();
                }
            }

            log.info("=======\n达到解冻分账的订单：{}========\n", JSON.toJSONString(list));

            List<String> orderNoList = new ArrayList<>();
            list.forEach(order -> {
                orderNoList.add(order.getOrderNo());
            });

            log.info("========远程获取订单分账接收方资金参数：{}=======", JSON.toJSONString(orderNoList));

            List<CustomerFundDetailVo> detailVos = iCustomerFundDetailService.getOrderFreezeProfit(orderNoList);

            if (ObjectUtil.isEmpty(detailVos)) {
                return;
            }
            if (ObjectUtil.isNotEmpty(detailVos)) {

                boolean flag = false;
                ProfitShareVo vo = null;
                OrderPayInfo payInfo = null;
                ProfitShareVo shareVo = null;
                ProfitShareReceiver receiver = null;
                List<ProfitShareReceiver> receiverList = null;

                for (OrderInfo order : list) {

                    //根据支付单号获取付款信息等
                    payInfo = payInfoService.getByOrderNo(order.getParentOrderNo());
                    if (payInfo == null) continue;

                    receiverList = new ArrayList<>();
                    for (CustomerFundDetailVo detailVo : detailVos) {
                        if (order.getOrderNo().equals(detailVo.getBizNo())) {

                            if (ObjectUtil.isEmpty(detailVo.getOpenId()) || ObjectUtil.isEmpty(detailVo.getAmount()))
                                continue;

                            receiver = new ProfitShareReceiver();
                            receiver.setType(ProfitsharingAddTypeEnum.PERSONAL_SUB_OPENID.name());
                            receiver.setAccount(detailVo.getOpenId());
                            receiver.setAmount(detailVo.getAmount());
                            receiver.setDescription("分润");
                            receiverList.add(receiver);
                        }
                    }
                    log.info("\n========分账接收方信息：{}=======\n", receiverList);
                    if (ObjectUtil.isEmpty(receiverList))
                        continue;

                    vo = new ProfitShareVo();
                    vo.setAppid(WechatV3Payment.sp_appid);
                    vo.setSub_mchid(payInfo.getSubMchid());
                    vo.setSub_appid(payInfo.getSubAppid());
//                    vo.setSub_mchid(WechatV3Payment.sub_mchid);
//                    vo.setSub_appid(WechatV3Payment.sub_appid);
                    vo.setTransaction_id(payInfo.getTransactionId());
                    vo.setOut_order_no(payInfo.getOrderNo());
                    vo.setReceivers(receiverList);
                    vo.setUnfreeze_unsplit(Boolean.FALSE);

                    flag = lastOrder(order.getParentOrderNo(), order.getOrderNo());
                    if (!flag)
                        vo.setUnfreeze_unsplit(Boolean.TRUE);

                    try {
                        shareVo = WechatV3Payment.V3ProfitsharingOrders(vo);
                        if (ObjectUtil.isNotEmpty(shareVo) && ("PROCESSING".equals(shareVo.getState()) || "FINISHED".equals(shareVo.getState()))) {
                            order.setIsShared(IsSharedEnum.shared.getKey());
                            this.updateById(order);
                            log.info("\n========请求分账成功=======\n");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new BaseException(e.getMessage());
                    }

                }
            }
        }
        return;
    }

    /**
     * 判断支付订单下是否存在其他待分账子订单
     *
     * @param parentOrderNo
     * @param orderNo
     * @return
     */
    private boolean lastOrder(String parentOrderNo, String orderNo) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("PARENT_ORDER_NO", parentOrderNo);
        queryWrapper.ne("ORDER_NO", orderNo);
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", IsSharedEnum.unShared.getKey());
        List<OrderInfo> list = jobOrderInfoMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(list))
            return true;
        return false;
    }

    /**
     * 解冻分润
     */
    @Override
    public void startOrderThaw() {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", IsSharedEnum.shared.getKey());
        List<OrderInfo> list = jobOrderInfoMapper.selectList(queryWrapper);
        log.info("\n========待解冻分润的订单：{}========\n", list);
        if (ObjectUtil.isNotEmpty(list)) {
            boolean flag = false;
            ProfitShareVo vo = null;
            OrderPayInfo payInfo = null;
            ProfitShareVo shareVo = null;
            List<String> orderNoList = new ArrayList<>();

            for (OrderInfo order : list) {

                flag = lastOrder(order.getParentOrderNo(), order.getOrderNo());
                if (!flag) {
                    payInfo = payInfoService.getByOrderNo(order.getParentOrderNo());
                    vo = new ProfitShareVo();
                    vo.setSub_mchid(payInfo.getSubMchid());
                    vo.setOut_order_no(payInfo.getOrderNo());
                    vo.setTransaction_id(payInfo.getTransactionId());
                    try {
                        shareVo = WechatV3Payment.V3ProfitsharingOrdersSearch(vo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (ObjectUtil.isNotEmpty(shareVo) && "FINISHED".equals(shareVo.getState())) {
                        orderNoList.add(order.getOrderNo());
                    }
                }
            }
            log.info("\n========获取完成解冻剩余资金的订单：{}========\n", JSON.toJSONString(orderNoList));
            if (ObjectUtil.isNotEmpty(orderNoList)) {
                Boolean aBoolean = iCustomerFundDetailService.setValidOrderProfit(orderNoList);
                log.info("\n==========远程调用解冻用户分润资金接口，parameter:{}==========\n===========result:{}===========\n",
                        JSONObject.toJSONString(orderNoList), JSONObject.toJSONString(aBoolean));
                if (aBoolean) {
                    UpdateWrapper wrapper = new UpdateWrapper<>();
                    wrapper.in("order_no", orderNoList);
                    wrapper.set("IS_SHARED", IsSharedEnum.thaw.getKey());
                    this.update(wrapper);
                    log.info("========解冻分润成功=========");

                }
            }

        }

    }

    @Override
    public int getWaitPayOrderCount(Long customerId) {
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.unpaid.getKey());
        queryWrapper.eq("customer_uid",customerId);
        return jobOrderInfoMapper.selectCount(queryWrapper);
    }

    /**
     * 查询可分账的订单
     *
     * @return
     */
    @Override
    public void searchProfitResult() {
        searchGoodProfitResult();
        searchRechargeProfitResult();
    }

    /**
     * 查询商品购买的分账结果
     */
    private void searchGoodProfitResult(){
        List<OrderInfo> list = null;
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        //queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", ProfitsharingStatusEnum.pending.getKey());
        queryWrapper.last("order by order_uid  limit 10 ");
        list = jobOrderInfoMapper.selectList(queryWrapper);
        log.info("\n=======待查询分账结果的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Iterator<OrderInfo> it = list.iterator();
            while(it.hasNext()){
                OrderInfo orderInfo = it.next();
                ProfitShareVo vo = new ProfitShareVo();
                vo.setSub_mchid(getSubMchId(orderInfo.getStoreId()));
                vo.setOut_order_no(orderInfo.getParentOrderNo());
                OrderPayInfo payInfo = orderPayInfoService.getByOrderNo(orderInfo.getParentOrderNo());
                if (payInfo != null){
                    vo.setTransaction_id(payInfo.getTransactionId());
                    try {
                        ProfitShareVo response = WechatV3Payment.V3ProfitsharingOrdersSearch(vo);
                        orderInfoShareService.save(vo.getOut_order_no(),"",ProfitSharingActionEnum.searchOrders.name(),0L,vo,response);
                        if (response != null && StringUtils.isEmpty(response.getCode())){
                            //如果完成分账，需要修改订单的分账状态
                            if ("FINISHED".equalsIgnoreCase(response.getState())) {
                                OrderInfo update = new OrderInfo();
                                update.setIsShared(ProfitsharingStatusEnum.share.getKey());
                                update.setOrderUid(orderInfo.getOrderUid());
                                jobOrderInfoMapper.updateById(update);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("查询分账{},异常===>{}",JSON.toJSONString(vo),e);
                    }
                }
            }
        }
    }


    /**
     * 查询充值的分账结果
     */
    private void searchRechargeProfitResult(){
        List<OrderRecharge> list = null;
        QueryWrapper<OrderRecharge> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", ProfitsharingStatusEnum.pending.getKey());
        queryWrapper.last("order by RECHARGE_UID  limit 10 ");
        list = orderRechargeMapper.selectList(queryWrapper);
        log.info("\n=======待查询分账结果的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Iterator<OrderRecharge> it = list.iterator();
            while(it.hasNext()){
                OrderRecharge orderInfo = it.next();
                ProfitShareVo vo = new ProfitShareVo();
                vo.setSub_mchid(getSubMchId(orderInfo.getStoreId()));
                vo.setOut_order_no(orderInfo.getParentOrderNo());
                OrderPayInfo payInfo = orderPayInfoService.getByOrderNo(orderInfo.getParentOrderNo());
                if (payInfo != null){
                    vo.setTransaction_id(payInfo.getTransactionId());
                    try {
                        ProfitShareVo response = WechatV3Payment.V3ProfitsharingOrdersSearch(vo);
                        orderInfoShareService.save(vo.getOut_order_no(),"",ProfitSharingActionEnum.searchOrders.name(),0L,vo,response);
                        if (response != null && StringUtils.isEmpty(response.getCode())){
                            //如果完成分账，需要修改订单的分账状态
                            if ("FINISHED".equalsIgnoreCase(response.getState())) {
                                OrderRecharge update = new OrderRecharge();
                                update.setIsShared(ProfitsharingStatusEnum.share.getKey());
                                update.setRechargeUid(orderInfo.getRechargeUid());
                                orderRechargeMapper.updateById(update);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.info("查询分账{},异常===>{}",JSON.toJSONString(vo),e);
                    }
                }
            }
        }
    }


    @Override
    public void requstProfit() {
        requestGoodsProfit();
        requestRechargeProfit();
    }


    @Override
    public void requstProfit(String orderNo) {
        List<OrderInfo> list = null;
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        queryWrapper.eq("order_no", orderNo);
        //queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", ProfitsharingStatusEnum.wait.getKey());
        queryWrapper.last(" and PAY_AMOUNT>0 order by order_uid  limit 10 ");
        list = jobOrderInfoMapper.selectList(queryWrapper);
        log.info("\n=======待分账的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Iterator<OrderInfo> it = list.iterator();
            while(it.hasNext()){
                OrderInfo orderInfo = it.next();
                if (orderInfo.getStoreId() != null){
                    OrderPayInfo payInfo = orderPayInfoService.getByOrderNo(orderInfo.getParentOrderNo());
                    PlatformStore store = platformStoreService.getById(orderInfo.getStoreId());
                    if (payInfo != null && store != null){
                        try {
                            if (profitShareOrder(orderInfo,payInfo.getTransactionId(),store)){
                                orderInfo.setIsShared(ProfitsharingStatusEnum.pending.getKey());
                                updateById(orderInfo);
                            }
                        } catch (Exception e) {
                            log.error("====订单号:{}调用分账异常===={}",orderInfo.getParentOrderNo(),e);
                        }
                    }
                }
            }
        }
    }

    /**
     * 购买商品请求分账
     */
    private void requestGoodsProfit(){
        List<OrderInfo> list = null;
        QueryWrapper<OrderInfo> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        //queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", ProfitsharingStatusEnum.wait.getKey());
        queryWrapper.last(" and PAY_AMOUNT>0 order by order_uid  limit 10 ");
        list = jobOrderInfoMapper.selectList(queryWrapper);
        log.info("\n=======待分账的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Iterator<OrderInfo> it = list.iterator();
            while(it.hasNext()){
                OrderInfo orderInfo = it.next();
                if (orderInfo.getStoreId() != null){
                    OrderPayInfo payInfo = orderPayInfoService.getByOrderNo(orderInfo.getParentOrderNo());
                    PlatformStore store = platformStoreService.getById(orderInfo.getStoreId());
                    if (payInfo != null && store != null){
                        try {
                            if (profitShareOrder(orderInfo,payInfo.getTransactionId(),store)){
                                orderInfo.setIsShared(ProfitsharingStatusEnum.pending.getKey());
                                updateById(orderInfo);
                            }
                        } catch (Exception e) {
                            log.error("====订单号:{}调用分账异常===={}",orderInfo.getParentOrderNo(),e);
                        }
                    }
                }
            }
        }
    }

    /**
     * 充值订单分账
     */
    private void requestRechargeProfit(){
        List<OrderRecharge> list = null;
        QueryWrapper<OrderRecharge> queryWrapper = Wrappers.query();
        queryWrapper.eq("order_status", OrderStatusEnum.effect.getKey());
        queryWrapper.eq("pay_status", PayStatusEnum.paid.getKey());
        //queryWrapper.eq("send_status", SendStatusEnum.receive.getKey());
        queryWrapper.eq("profit_sharing", ProfitSharingEnum.Y.name());
        queryWrapper.eq("is_shared", ProfitsharingStatusEnum.wait.getKey());
        queryWrapper.last(" and PAY_AMOUNT>0 order by RECHARGE_UID  limit 10 ");
        list = orderRechargeMapper.selectList(queryWrapper);
        log.info("\n=======待分账的订单：{}========\n", JSON.toJSONString(list));
        if (ObjectUtil.isNotEmpty(list)) {
            Iterator<OrderRecharge> it = list.iterator();
            while(it.hasNext()){
                OrderRecharge orderInfo = it.next();
                if (orderInfo.getStoreId() != null){
                    OrderPayInfo payInfo = orderPayInfoService.getByOrderNo(orderInfo.getParentOrderNo());
                    PlatformStore store = platformStoreService.getById(orderInfo.getStoreId());
                    if (payInfo != null && store != null){
                        try {
                            if (profitShareOrder(orderInfo,payInfo.getTransactionId(),store)){
                                orderInfo.setIsShared(ProfitsharingStatusEnum.pending.getKey());
                                orderRechargeMapper.updateById(orderInfo);
                            }
                        } catch (Exception e) {
                            log.error("====订单号:{}调用分账异常===={}",orderInfo.getParentOrderNo(),e);
                        }
                    }
                }
            }
        }
    }


    /**
     * 请求分账
     * @param orderInfo
     * @return
     */
    private boolean profitShareOrder(OrderInfo orderInfo, String transactionId, PlatformStore organ) throws Exception {
        log.info("请求分账订单ID={}",orderInfo.getOrderUid());
        ProfitShareVo profit = new ProfitShareVo();
        String sub_mchid = getSubMchId(orderInfo.getStoreId());
        profit.setSub_mchid(sub_mchid);
        ProfitShareVo vo = new ProfitShareVo();
        //先查询分账比例，再执行分账
        profit = WechatV3Payment.V3ProfitsharingMerchantConfigs(profit);
        Long ratio = Constants.SHARE_PROFIT_RATE;
        if (profit.getMax_ratio() == null || profit.getMax_ratio().intValue()==0){
            log.error("该商户暂未开通分账功能，不能进行分账==>{}",JSONObject.toJSONString(profit));
            return false;
        }
        ratio = profit.getMax_ratio().longValue();
        Long amount = BigDecimal.valueOf(orderInfo.getPayAmount()*ratio/10000.0).longValue();
        if (amount>0){
            vo.setSub_mchid(sub_mchid);
            vo.setAppid(WechatV3Payment.sp_appid);
            vo.setSub_appid(WechatV3Payment.sub_appid);
            vo.setTransaction_id(transactionId);
            vo.setOut_order_no(orderInfo.getParentOrderNo());
            ProfitShareReceiver receiver = new ProfitShareReceiver();
            receiver.setType(ProfitsharingAddTypeEnum.MERCHANT_ID.name());
            receiver.setAccount(organ.getMerchantId());
            receiver.setAmount(amount);
            receiver.setName(organ.getMerchantName());
            receiver.setDescription(OrderTypeEnum.getNameByKey(orderInfo.getOrderType()));
            List<ProfitShareReceiver> list = new ArrayList<ProfitShareReceiver>();
            list.add(receiver);
            vo.setReceivers(list);
            vo.setUnfreeze_unsplit(Boolean.TRUE);
            ProfitShareVo response = WechatV3Payment.V3ProfitsharingOrders(vo);
            orderInfoShareService.save(orderInfo.getParentOrderNo(),"",ProfitSharingActionEnum.profitsharing.name(),amount,vo,response);
            if (response != null && StringUtils.isEmpty(response.getCode())){
                return true;
            }
        }
        return false;
    }

    /**
     * 获得门店对应的子商户号
     * @param storeId
     * @return
     */
    private String getSubMchId(Long storeId){
        String subMchid = WechatV3Payment.sub_default_mchid;
        if (storeId != null) {
            PlatformStore store = platformStoreService.getById(storeId);
            if (store != null && StringUtils.isNotEmpty(store.getMerchantId())) {
                subMchid = store.getMerchantId();
            }
        }
        return subMchid;
    }

    private boolean profitShareOrder(OrderRecharge orderInfo, String transactionId, PlatformStore organ) throws Exception {
        log.info("请求分账订单ID={}",orderInfo.getRechargeId());
        String sub_mchid = getSubMchId(orderInfo.getStoreId());
        ProfitShareVo profit = new ProfitShareVo();
        profit.setSub_mchid(sub_mchid);
        ProfitShareVo vo = new ProfitShareVo();
        //先查询分账比例，再执行分账
        profit = WechatV3Payment.V3ProfitsharingMerchantConfigs(profit);
        Long ratio = Constants.SHARE_PROFIT_RATE;
        if (profit.getMax_ratio() == null || profit.getMax_ratio().intValue()==0){
            log.error("该商户暂未开通分账功能，不能进行分账==>{}",JSONObject.toJSONString(profit));
            return false;
        }
        ratio = profit.getMax_ratio().longValue();
        Long amount = BigDecimal.valueOf(orderInfo.getPayAmount()*ratio/10000.0).longValue();
        if (amount>0){
            vo.setSub_mchid(sub_mchid);
            vo.setAppid(WechatV3Payment.sp_appid);
            vo.setSub_appid(WechatV3Payment.sub_appid);
            vo.setTransaction_id(transactionId);
            vo.setOut_order_no(orderInfo.getParentOrderNo());
            ProfitShareReceiver receiver = new ProfitShareReceiver();
            receiver.setType(ProfitsharingAddTypeEnum.MERCHANT_ID.name());
            receiver.setAccount(organ.getMerchantId());
            receiver.setAmount(amount);
            receiver.setName(organ.getMerchantName());
            receiver.setDescription(OrderTypeEnum.getNameByKey(OrderTypeEnum.recharge.getKey()));
            List<ProfitShareReceiver> list = new ArrayList<ProfitShareReceiver>();
            list.add(receiver);
            vo.setReceivers(list);
            vo.setUnfreeze_unsplit(Boolean.TRUE);
            ProfitShareVo response = WechatV3Payment.V3ProfitsharingOrders(vo);
            orderInfoShareService.save(orderInfo.getParentOrderNo(),"",ProfitSharingActionEnum.profitsharing.name(),amount,vo,response);
            if (response != null && StringUtils.isEmpty(response.getCode())){
                return true;
            }
        }
        return false;
    }

}
